// pages/combo/newdetail.js
import Honey from '../../utils/honey';
import Event from '../../utils/event'
let WxParse = require('../../wxParse/wxParse.js');
import util from '../../utils/util.js'


const app = getApp();
const honey = new Honey();
const event = new Event();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shareMessage: {}, //分享配置信息
    scrollflag: '', //顶部导航当前选择
    scrollNum: '', //滚动标签变量，点击滚动到该id位置
    opacity: '', //顶部导航透明度控制
    scrollarr: [], //滚动到各个导航标签距离顶部的距离
    lock: false, //顶部导航点击加锁，防止滚动触发事件
    // storeId: '', //当前机构ID
    store: '', //机构详情信息
    imgArr: [], //机构介绍图片列表
    openShow: true, //页面加载幕布显示隐藏
    pageNo: 1, //当前页
    pageSize: 5, //每页记录数
    isLoad: true,
    good: {}, //商品全部信息
    combo: {}, //商品信息
    comboId: '', //当前商品ID
    commentList: [], //评价列表
    lookMoreStore: false, //查看更多门店控制参数
    storeListarr: [], //商家门店列表
    storeList: [], //商家缩略门店列表（仅显示两家）
    couponList: [], //当前可使用兑换券数据
    couponListIdx: -1, //当前选择兑换券索引
    scrolltop: '', //当前滚动位置
    phone: '', //手机号
    phoneUntying: false, //手机解绑框
    user: '', //用户信息
    payMoney: 0, //实付金额
    paymentShow: false, //支付框控制显示
    discountsShow: false, //兑换券框控制显示
    disabled: true, //余额支付是否可用参数
    payment: 2, //支付方式：2为微信支付，1为余额支付,3为兑换券抵用
    items: [{
        name: '2',
        value: '微信支付',
        checked: 'true'
      },
      {
        name: '1',
        value: '余额支付'
      },

    ], //支付方式单选内容
    headPicImageViewSuffix: util.imageViewToWidthFunc(500),
    evaluatePicImageViewSuffix: util.imageViewToWidthFunc(100),
    seatMealPicImageViewSuffix: util.imageViewToWidthFunc(150),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const that = this;

    if (options.check_code && !wx.getStorageSync('user')) {
      wx.setStorageSync('checkCode', options.check_code);
      var pages = getCurrentPages(); //获取加载的页面
      var currentPage = pages[pages.length - 1]; //获取当前页面的对象
      var url = `/${currentPage.route}`; //当前页面url
      var toUrl = `${url}?id=${currentPage.options.id}`; //如果要获取url中所带的参数可以查看options
      console.log(toUrl);
      if (!wx.getStorageSync('user')) {
        wx.setStorageSync('pagesUrl', toUrl)
        wx.switchTab({
          url: '/pages/index/index',
        })
        return;
      }
    }

    that.setData({
      user: wx.getStorageSync('user'),
      phone: wx.getStorageSync('phone') ? wx.getStorageSync('phone') : ''
    })

    wx.showLoading({
      title: '加载中...',
    })
    const comboId = options.id;
    const imgReg = /<img.*?(?:>|\/>)/gi;
    const srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
    wx.getLocation({
      type: 'gcj02',
      complete: function(res) {
        that.setData({
          longitude: res.longitude ? res.longitude : '',
          latitude: res.latitude ? res.latitude : '',
          user: wx.getStorageSync('user')
        })
        honey.post({
          alias: 'getGoodsInfo',
          data: {
            goods_id: comboId,
            lat: res.latitude ? res.latitude : '',
            lng: res.longitude ? res.longitude : '',
          },
          success: function(res) {
            let combo = res.data.data.goodsInfo;
            WxParse.wxParse('article', 'html', combo.content, that, 17);
            // combo.content = combo.content.replace('<br />', '').replace(/\<img/gi, '<img style="max-width:100%;height:auto;margin:0 auto;display:block;" ').replace('<br/></p>', '</p>');
            WxParse.wxParse('notice', 'html', combo.notice, that, 17);
            // combo.notice = combo.notice.replace('<br />', '').replace(/\<img/gi, '<img style="max-width:100%;height:auto;margin:0 auto;display:block;" ').replace('<br/></p>', '</p>');
            let payMoney = (combo.only_price * 1 - combo.max_health * 1).toFixed(2);
            if(wx.getStorageSync('user')){
              var disabled = that.data.user.info.amount * 1 >= payMoney * 1 ? false : true;
            }else{
              var disabled=false;
            }

            let good = res.data.data;
            let storeListarr = [];
            for (let i = 0; i < good.storeList.length; i++) {
              storeListarr = [...storeListarr, ...good.storeList[i].shop_list];
            }
            let storeList = storeListarr.slice(0, 2)
            that.setData({
              storeList,
              storeListarr,
              comboId,
              combo,
              good,
              disabled,
              payMoney,
            })
            that.getCommentList();
            if(wx.getStorageSync('user')){
              that.getCouponList();
            }
            that.getShareInfo();

            //套餐，评价，介绍，推荐距离顶部位置数组


            setTimeout(() => {
              wx.hideLoading();
              that.setData({
                openShow: false
              })
            }, 500)
          }
        })
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    const that = this;



  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    const that = this;
    return {
      title: that.data.shareMessage.title,
      path: `/pages/combo/newdetail?id=${that.data.comboId}&check_code=${that.data.user.check_code}`,
      imageUrl: that.data.shareMessage.image
    }
  },

  //顶部导航点击切换事件
  updateNum: function(e) {
    const that = this;
    that.setData({
      scrollNum: e.currentTarget.dataset.id,
      scrollflag: e.currentTarget.dataset.id,
      lock: true,
    })
  },

  //滚动事件
  scrollView: function(e) {
    const that = this;
    let scrolltop = e.detail.scrollTop;
    let scrollopacity = e.detail.scrollTop / 280;
    that.setData({
      opacity: scrollopacity,
    })
    for (let i = 0; i < that.data.scrollarr.length; i++) {
      if (scrolltop < that.data.scrollarr[i] && !that.data.lock) {
        that.setData({
          scrollflag: 'scroll' + i
        })
        break;
      }
    }
    that.setData({
      lock: false,
      scrolltop
    })
  },

  // //点击机构介绍图片大图展示
  // prevImage: function () {
  //   const that = this;
  //   wx.previewImage({
  //     current: that.data.imgArr[0], // 当前显示图片的http链接
  //     urls: that.data.imgArr // 需要预览的图片http链接列表
  //   })
  // },

  //分店导航按钮
  toNavigation: function(e) {
    const that = this;
    const latitude = e.currentTarget.dataset.lat * 1;
    const longitude = e.currentTarget.dataset.lng * 1;
    const name = e.currentTarget.dataset.name;
    wx.openLocation({
      latitude,
      longitude,
      name,
    })
  },

  //分店电话按钮
  callPhone: function(e) {
    const that = this;
    const phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },

  //获取机构评价列表数据
  getCommentList: function() {
    const that = this;
    if (that.data.isLoad) {
      that.setData({
        isLoad: false
      })
      honey.post({
        alias: 'commentList',
        data: {
          page: that.data.pageNo,
          page_size: that.data.pageSize,
          goods_id: that.data.comboId,
        },
        success: function(res) {
          that.setData({
            commentList: honey.mergeArray(that.data.commentList, res.data.data.comment_list),
            pageNo: that.data.pageNo + 1,
            isLoad: (res.data.data.comment_list.length < that.data.pageSize ? false : true)
          })
          let scrollarr = [];
          for (let i = 1; i <= 4; i++) {
            wx.createSelectorQuery().select('#scroll' + i).fields({
              rect: true,
            }, function(res) {
              scrollarr.push(res.top);
              if (i == 3) {
                that.setData({
                  scrollarr
                })
              }
            }).exec()
          }
        }
      })
    }
  },

  //点击打开图片
  previewImage: function(e) {
    const that = this;
    const image = e.currentTarget.dataset.image;
    console.log(image);
    const index = e.currentTarget.dataset.index;
    console.log(index);
    wx.previewImage({
      current: image, // 当前显示图片的http链接
      urls: that.data.commentList[index].smeta.image // 需要预览的图片http链接列表
    })
  },

  //点击查看更多门店
  showMoreStore: function() {
    const that = this;
    if (that.data.lookMoreStore){
      that.setData({
        lookMoreStore: false
      })
    }else{
      that.setData({
        lookMoreStore: true
      })
    }
    
    let scrollarr = [];
    for (let i = 1; i <= 4; i++) {

      wx.createSelectorQuery().select('#scroll' + i).boundingClientRect(function(rect) {
        scrollarr.push(rect.top * 1 + that.data.scrolltop * 1);
        if (i == 3) {
          that.setData({
            scrollarr
          })
        }
      }).exec()
    }
  },


  //打开支付框
  toBuy: function() {
    const that = this;
    if (!that.data.user) {
      const user = honey.checkLogin('/pages/combo/newdetail?id=' + that.data.comboId, false);
      return;
    }
    event.emit('refreshUserInfo', 'userInfo');
    wx.showLoading({
      title: '请稍后',
      mask: true
    })
    if(that.data.items.length==3){
      let items=that.data.items;
      items[0].checked=false,
      items[1].checked = false,
      items[2].checked = true,
      that.setData({
         items,
      })
      that.radioChange({detail:{value:3}})
    }
      
    honey.post({
      alias: 'getUserInfo',
      success: function(res) {
        const user = Object.assign(wx.getStorageSync('user'), res.data.data);
        wx.setStorageSync('user', user);

        that.setData({
          user: user,
          paymentShow: true,
        })
        wx.hideLoading();
      }
    })
  },

  //关闭手机绑定框
  clearUntyingPhone: function() {
    that.setData({
      phoneUntying: false,
    })
  },

  //不同账号绑定同一个手机号情况接口
  untyingPhone: function() {
    const that = this;
    honey.post({
      alias: 'unbindUserPhone',
      data: {
        mobile: that.data.unPhone
      },
      success: function(res) {
        wx.showToast({
          title: '绑定成功',
          icon: 'none'
        })
        wx.setStorageSync('phone', that.data.unPhone);
        that.setData({
          phoneUntying: false,
        })
        that.toBuy();
      }
    })
  },

  //手机号授权绑定
  getPhoneNumber: function(e) {
    console.log(111)
    const that = this;
    console.log(e);
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      console.log(222)
      const phone = e.detail;
      honey.post({
        alias: 'bindUserPhone',
        data: {
          encrypt: phone.encryptedData,
          iv: phone.iv,
          session_key: wx.getStorageSync('sessionKey')
        },
        success: function(res) {
          if (res.data.data.had_bind == 1) {
            that.setData({
              phoneUntying: true,
              unPhone: res.data.data.mobile,
              message: res.data.message
            })
          } else {
            wx.setStorageSync('phone', res.data.data.userInfo.mobile);
            that.setData({
              phone: res.data.data.userInfo.mobile
            })
            that.toBuy();
          }
        }
      })
    }
  },

  //关闭支付框
  closeCashier: function() {
    const that = this;
    that.setData({
      paymentShow: false
    })
  },

  //前往首页
  toIndex: function() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  saveOrder: function() {
    const that = this;
    wx.showLoading({
      title: '支付中',
      mask: true
    })
    honey.post({
      alias: 'createOrder',
      data: {
        goods_id: that.data.comboId,
        health_pay: that.data.combo.max_health,
        pay_type: that.data.payment == 2 ? 'wx_pay' : that.data.payment == 1 ? 'amount_pay' : 'coupon_pay',
        coupon_id: that.data.couponListIdx == -1 ? '' : that.data.couponList[that.data.couponListIdx].id
      },
      success: function(res) {
        if (!res.data.data.payParam) {
          let orderId = res.data.data.order_sn;
          wx.navigateTo({
            url: '/pages/pay/paySuccess?id=' + orderId,
          })
        } else {
          var payParam = res.data.data.payParam;
          wx.requestPayment({
            timeStamp: payParam.timeStamp,
            nonceStr: payParam.nonceStr,
            package: payParam.package,
            signType: payParam.signType,
            paySign: payParam.paySign,
            success: function() {
              event.emit('refreshUserInfo', 'userInfo');
              wx.navigateTo({
                url: '/pages/pay/paySuccess?id=' + res.data.data.order_sn,
              })
            },
            fail: function(res) {
              event.emit('refreshUserInfo', 'userInfo');
              wx.showToast({
                title: '支付失败',
                image: '/res/images/icon-shibai.png'
              })
              setTimeout(() => {
                wx.navigateTo({
                  url: '/pages/mine/myPurchase',
                })
              }, 1500)
            }
          })
        }
      },
      complete: function() {
        event.emit('refreshUserInfo', 'userInfo');
        wx.hideLoading();
      }
    })



  },

  //支付方式选择事件
  radioChange: function(e) {
    const that = this;
    that.setData({
      payment: e.detail.value
    })
    if (e.detail.value==3){
      that.setData({
        couponListIdx: 0
      })
    }else{
      that.setData({
        couponListIdx: -1
      })
    }
      
  },

  //打开兑换券选择框
  openTicket: function() {
    const that = this;
    that.setData({
      discountsShow: true,
    })
  },

  //获取当前商品可用兑换卷
  getCouponList: function() {
    const that = this;
    honey.post({
      alias: 'getCouponList',
      data: {
        goods_id: that.data.comboId,
        status: 0
      },
      success: function(res) {
        that.setData({
          couponList: res.data.data.couponList,
        })
        if (res.data.data.couponList.length > 0) {
          that.setData({
            items: [...that.data.items,
              {
                name: '3',
                value: '兑换券抵用'
              }
            ],

          })
        }
      }
    })
  },

  //选择兑换券
  selectTicket: function(e) {
    const that = this;
    let couponListIdx = e.currentTarget.dataset.idx;
    that.setData({
      couponListIdx,
      discountsShow: false
    })
  },

  //分享信息配置
  getShareInfo: function() {
    const that = this;
    honey.post({
      alias: 'getShareInfo',
      data: {
        object_id: that.data.comboId,
        type: 1
      },
      success: function(res) {
        that.setData({
          shareMessage: res.data.data
        })
      }
    })
  }

})